from apps.vadmin.op_drf.response import SuccessJsonResponse
from apps.vadmin.op_drf.viewsets import CustomModelViewSet
from apps.vadmin.stock.models.stock import StockList
import pandas as pd
import os

class StockViewSet(CustomModelViewSet):
    """
    角色管理 的CRUD视图
    """

    def day(self,request):
            # 获取参数
            dic = request.data.get('userId')
            symbol = None
            symbol_type = None
            account_id = None
            sql = "select   1 id,   trading_day, sum(pnl_today) pnl_today, sum(pnl_hold) pnl_hold, sum(pnl_trade) pnl_trade  from stock_list2  where 1=1"

            if symbol != None:
                sql += "symbol='" + symbol + "'"
            if symbol_type != None:
                sql += "symbol_type='" + symbol_type + "'"
            if account_id != None:
                sql += "account_id='" + account_id + "'"
            sql += " group by   trading_day   "

            results = StockList.objects.raw(sql)
            li = []
            for result in results:
                row = {}
                row['tradingDay'] = str(result.trading_day)
                row['pnlToday'] = result.pnl_today
                row['pnlTrade'] = result.pnl_trade
                row['pnlHold'] = result.pnl_hold
                li.append(row)

            return SuccessJsonResponse(li)

    def time(self, request):
            sql = "select 1 id, grid_time, sum(pnl_today) pnl_today, sum(pnl_hold) pnl_hold, sum(pnl_trade) pnl_trade from stock_list2  where    1=1 "
            symbol = request.POST.get("symbol")
            symbol_type = request.POST.get("symbolType")
            account_id = request.POST.get("account_id")
            trading_day = request.POST.get("trading_day")

            if symbol != None:
                sql += "symbol='" + symbol + "'"
            if symbol_type != None:
                sql += "symbol_type='" + symbol_type + "'"
            if account_id != None:
                sql += "account_id='" + account_id + "'"
            if trading_day != None:
                sql += "trading_day='" + trading_day + "'"
            sql += " group by    grid_time   "

            results = StockList.objects.raw(sql)
            li = []
            for result in results:
                row = {}

                row['gridTime'] = result.grid_time
                row['pnlToday'] = result.pnl_today
                row['pnlTrade'] = result.pnl_trade
                row['pnlHold'] = result.pnl_hold
                li.append(row)
            return SuccessJsonResponse(li)

    def gettype(self,request):

            results = StockList.objects.raw(
                " select 1 id, account_id from ( select distinct account_id  account_id"
                " from stock_list2 ) tab ")

            dicType = {}
            li = []
            for result in results:
                row = {}
                row["value"] = str(result.account_id)
                row["label"] = str(result.account_id)
                li.append(row)
            dicType['label'] = li

            results = StockList.objects.raw(
                " select 1 id, symbol from ( select distinct symbol  symbol"
                " from stock_list2 ) tab ")
            li = []
            for result in results:
                row = {}
                row["value"] = result.symbol
                row["label"] = result.symbol
                li.append(row)
            dicType['label2'] = li

            results = StockList.objects.raw(
                " select 1 id, symbol_type from ( select distinct symbol_type  symbol_type"
                " from stock_list2 ) tab ")
            li = []
            for result in results:
                row = {}
                row["value"] = result.symbol_type
                row["label"] = result.symbol_type
                li.append(row)
            dicType['label3'] = li
            return SuccessJsonResponse(dicType)





    def risk_summary(self,request):
        if request.method != "GET":
            print(request.method)
            return
        # df = pd.read_csv("~/data/csv_folder/query_pnleod_accounts_date.csv")
        # df = pnl_api.eq_pnl_reader.query_rt_risk_summary()  # account_names, date)

        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        TEMPLATE_DIR = os.path.join(BASE_DIR, 'stock/risk_summary.csv')
        print(TEMPLATE_DIR)
        df = pd.read_csv(TEMPLATE_DIR)
        # df.to_csv("~/data/csv_folder/risk_summary.csv")
        data_dict = {"data": [df.iloc[i].to_json() for i in range(df.shape[0])]}
        return SuccessJsonResponse(data_dict)

    def risk_secondary_name_mapping(self,request):
        if request.method != "GET":
            print(request.method)
            return
        # MODIFY RETURN HERE
        risk_secondary_name_mapping = {
            "单股市值风险": ["symbol_single_stock", "mv_single_stock", "ratio_single_stock"],
            "个股持仓比例风险": ["symbol_share_hold", "mv_share_hold", "ratio_share_hold"],
            "行业市值风险": ["industry", "mv_industry", "ratio_industry"],
            "市场市值情况": [
                "mv_sum",
                "mv_sze",
                "mv_sse",
                "mv_cyb",
                "mv_kcb",
                "ratio_mv_sze",
                "ratio_mv_sse",
                "ratio_mv_cyb",
                "ratio_mv_kcb",
            ],
            "交易相关": [
                "cnt_stock_hold",
                "cnt_stock_hold_prev",
                "cnt_order",
                "cnt_cncl",
                "ratio_cncl",
                "tovr",
                "ratio_tovr",
                "ratio_cncl_tovr",
                "ratio_cross_cncl",
                "ratio_limit_cncl",
                "ratio_cross_div_limit",
            ],
        }
        data_dict = {"data": risk_secondary_name_mapping}
        return SuccessJsonResponse(data_dict)

    def risk_show_name_mapping(self,request):
        if request.method != "GET":
            print(request.method)
            return
        # MODIFY RETURN HERE
        secondary_name_mapping = {
            "symbol_single_stock": "最大市值股票名称",
            "mv_single_stock": "最大个股市值",
            "ratio_single_stock": "最大个股市值占比",
            # "mv_share_hold": "个股持仓比例风险",
            "symbol_share_hold": "最大股本占比股票名称",
            "mv_share_hold": "最大股本占比股票市值",
            "ratio_share_hold": "最大股本占比股票占股本比例",
            "industry": "最大单一行业权重行业名称",
            "mv_industry": "最大单一行业市值",
            "ratio_industry": "最大单一行业权重比率",
            "mv_sum": "总市值",
            "mv_sze": "深市总市值",
            "mv_sse": "沪市总市值",
            "mv_cyb": "深市总市值",
            "mv_kcb": "沪市总市值",
            "ratio_mv_sze": "深市市值占比",
            "ratio_mv_sse": "沪市市值占比",
            "ratio_mv_cyb": "深市市值占比",
            "ratio_mv_kcb": "沪市市值占比",
            "cnt_stock_hold": "当日持股数量",
            "cnt_stock_hold_prev": "前日持股数量",
            "cnt_order": "当日委托总数",
            "cnt_cncl": "当日撤单总数",
            "ratio_cncl": "当日撤单率",
            "tovr": "当日交易额",
            "ratio_tovr": "当日换手率",
            "ratio_cncl_tovr": "当日撤单率(金额)",
            "ratio_cross_cncl": "对价单撤单率(次数)",
            "ratio_limit_cncl": "限价单撤单率(次数)",
            "ratio_cross_div_limit": "对价单/限价单",
        }
        data_dict = {"data": secondary_name_mapping}
        return SuccessJsonResponse(data_dict)
